package com.tianlh.quartz;

import org.quartz.Scheduler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

/**
 * @author 黑子
 * @Date 2018/2/28 9:28
 */
@Component
public class SchedulerManager implements InitializingBean {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;

    private static Scheduler scheduler;

    @Override
    public void afterPropertiesSet() throws Exception {
        scheduler = schedulerFactoryBean.getScheduler();
        scheduler.start();
    }

    public Scheduler getScheduler(){
        return scheduler;
    }

    /**
     * 启动所有定时任务
     */
    public void startJobs() {
        try {
            scheduler.start();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭所有定时任务
     */
    public void shutdownJobs() {
        try {
            if(!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

